import request from '@/utils/request'
import store from '@/store/index'
import router from '@/router/index'

// 登录
export const login = (data) => {
  return request({
    method: 'post',
    url: '/front/user/login',
    data: `phone=${data.phone}&password=${data.password}`
  })
}

// 获取用户信息
export const getUserInfo = (data) => {
  return request({
    method: 'get',
    url: '/front/user/getInfo'
  })
}

// 获取用户信息
export const logout = (data) => {
  return request({
    method: 'post',
    url: '/front/user/logout'
  })
}

// 刷新token
let promiseRT = null // 保存请求刷新token的promise对象
let refreshing = false // 标志是否已经启动了刷新动作
export const refreshToken = () => {
  if (refreshing) {
    return promiseRT
  }

  refreshing = true
  promiseRT = request({
    method: 'post',
    url: '/front/user/refresh_token',
    params: { refreshtoken: store.state.tokenInfo.refresh_token }
  }).then(res => {
    if (res.data.success) {
      // 成功
      store.commit('saveTokenInfo', res.data.content)
    } else {
      // 没有拿到token
      router.push({
        name: 'login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      })
      throw new Error('刷新token失败')
    }
  }).finally(() => {
    refreshing = false // 重置标识位
  })
}

// 查询用户列表
export const queryUsers = (data) => {
  return request({
    method: 'post',
    url: '/boss/user/getUserPages',
    data
  })
}

// 启用用户
export const enableUser = (userId) => {
  return request({
    method: 'get',
    url: '/boss/user/enableUser',
    params: { userId }
  })
}

// 封禁用户
export const forbidUser = (userId) => {
  return request({
    method: 'post',
    url: '/boss/user/forbidUser',
    data: { userId }
  })
}

// 获取用户拥有的角色信息
export const getUserRoles = (userId) => {
  return request({
    method: 'get',
    url: '/boss/role/getRolesWithUserPermission',
    params: { userId }
  })
}

// 分配角色
export const allocateUserRoles = (data) => {
  return request({
    method: 'post',
    url: '/boss/role/allocateUserRoles',
    data
  })
}
